//
//  SWCacheManager.swift
//  MiU
//
//  Created by linhan on 16/1/14.
//  Copyright © 2016年 MiU. All rights reserved.
//

import Foundation



enum SWCacheType:String
{
    case Default
    case VideoList
    case FeedFlow
    case EventPhotoList
}

//private let _manager = SWCacheManager()
private var _manager:SWCacheManager?
class SWCacheManager: NSObject
{
    var uid:String = "Default"
    
    private var cacheDirectory:String = ""
    
    //class var manager
    class func sharedManager() -> SWCacheManager
    {
        _manager = _manager ?? SWCacheManager()
        return _manager!
    }
    
    override init()
    {
        super.init()
        setup()
    }
    
    //写入对象到本地缓存文件
    func writeCache(_ obj:Any, type:SWCacheType, tag:String? = nil)
    {
        let path:String = getPath(type, suffix:tag)
        writeCache(obj, path:path)
    }
    
    func writeCache(_ obj:Any, path:String)
    {
        NSKeyedArchiver.archiveRootObject(obj, toFile: path)
    }
    
    //从本地缓存文件读取并模型化
    func readCache(_ type:SWCacheType, tag:String? = nil) -> Any?
    {
        return readCache(getPath(type, suffix:tag))
    }
    
    func readCache(_ path:String) -> Any?
    {
        return NSKeyedUnarchiver.unarchiveObject(withFile: path)
    }
    
    func removeCache(_ type:SWCacheType, tag:String? = nil)
    {
        removeCache(getPath(type, suffix:tag))
    }
    
    func removeCache(_ path:String)
    {
        try? FileManager.default.removeItem(atPath: path)
    }
    
    //获取缓存文件路径
    private func getPath(_ type:SWCacheType, suffix:String? = nil) -> String
    {
        var fileName:String = type.rawValue
        if let suffix = suffix , suffix != ""
        {
            fileName += "_\(suffix)"
        }
        fileName += ".archiver"
        return "\(cacheDirectory)/\(fileName)"
    }
    
    private func setup()
    {
        cacheDirectory = (NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).valueAt(0) ?? "") + "/Archiver"
        let fileManager = FileManager.default
        if !fileManager.fileExists(atPath: cacheDirectory)
        {
            try? fileManager.createDirectory(atPath: cacheDirectory, withIntermediateDirectories: true, attributes: nil)
        }
    }
    
    
    
    
    
    
    
}
